const { Nuxt, Builder } = require('nuxt')
const bodyParser = require('body-parser')
const app = require('express')()
var logger = require('./logger/log')
var loggerConfig = require('./logger/loggerconfig')
var uuid = require('node-uuid')

console.log('process.env.NODE_ENV------>')
console.log(process.env.NODE_ENV)


app.set('port', (process.env.PORT || 3000))
// Body parser，用来封装 req.body
app.use(bodyParser.json())
var cookieParser = require('cookie-parser')
app.use(cookieParser())

global.logger = logger.logger

function assignId (req, res, next) {
  req.id = uuid.v4().substr(0, 8)
  next()
};

// winston日志接入
var hl = logger.morgan(loggerConfig.template, {stream: logger.stream,
  skip: function (req, res) {
    return res.statusCode === 304 || /(.js|.css|.jpg|.png|.ico)/.test(req.url)
  }
})
app.use(assignId)
app.use(hl)

// Require API routes
const apiRoutes = require('./server/routes/api')

app.use('/api', apiRoutes)

// Import API Routes

// 我们用这些选项初始化 Nuxt.js：
const isProd = process.env.NODE_ENV !== 'development'
const config = require('./nuxt.config.js')
config.dev = !isProd
const nuxt = new Nuxt(config)
// 生产模式不需要 build
if (!isProd) {
  const builder = new Builder(nuxt)
  builder.build()
}
app.use(nuxt.render)

const server = app.listen(app.get('port'), function() {
  const address = server.address().address
  const port = server.address().port
  global.logger.info("Start server listening on " + address + ":" + port)
})
